const Transaction = require("../models/Transaction");

class TransactionService {
  // 创建交易
  async createTransaction({ amount, description }) {
    try {
      return await Transaction.create({
        amount,
        description,
        userId: req.user.id, // 设置交易关联的用户ID
      });
    } catch (error) {
      console.error("创建交易时出错：", error);
      throw error;
    }
  }

  // 获取所有交易
  async getAllTransactions() {
    try {
      return await Transaction.findAll();
    } catch (error) {
      console.error("获取所有交易时出错：", error);
      throw error;
    }
  }

  // 获取特定交易
  async getTransactionById(id) {
    try {
      return await Transaction.findByPk(id);
    } catch (error) {
      console.error("获取特定交易时出错：", error);
      throw error;
    }
  }

  // 更新交易
  async updateTransaction({ id, amount, description }) {
    try {
      const transaction = await Transaction.findByPk(id);
      if (!transaction) {
        return false;
      }
      // 更新交易信息
      transaction.amount = amount;
      transaction.description = description;
      return await transaction.save();
    } catch (error) {
      console.error("更新交易时出错：", error);
      throw error;
    }
  }

  // 删除交易
  async deleteTransaction(id) {
    try {
      const transaction = await Transaction.findByPk(id);
      if (!transaction) {
        return false;
      }
      // 删除交易
      return await transaction.destroy();
    } catch (error) {
      console.error("删除交易时出错：", error);
      throw error;
    }
  }

  // 获取用户自己的交易
  async getUserTransactions() {
    try {
      const userId = req.user.id;
      return await Transaction.findAll({ where: { userId } });
    } catch (error) {
      console.error("获取用户自己的交易时出错：", error);
      throw error;
    }
  }

  // 用户删除自己的交易
  async deleteUserTransaction(id) {
    try {
      const userId = req.user.id;
      const transaction = await Transaction.findOne({ where: { id, userId } });
      if (!transaction) {
        return false;
      }
      return await transaction.destroy();
    } catch (error) {
      console.error("用户删除自己的交易时出错：", error);
      throw error;
    }
  }
}

module.exports = new TransactionService();
